<template>
  <section class="wh-full">
    <header class="flex-b plr-16px h-64px bg-#fff rd-4px">
      <a-form ref="searchRormRef" :model="searchFormState" name="horizontal_login" layout="inline" autocomplete="off" @finish="onFinishSearch">
        <a-form-item label="标题" name="title">
          <a-input v-model:value="searchFormState.title"> </a-input>
        </a-form-item>

        <a-form-item label="关键词" name="keywords">
          <a-input v-model:value="searchFormState.keywords"> </a-input>
        </a-form-item>
        <a-form-item label="分类" name="classificationId">
          <a-select ref="select" v-model:value="searchFormState.classificationId" placeholder="分类" :options="classificationOptions" style="width: 220px"></a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button :disabled="disabledSeachBtn" type="primary" html-type="submit">搜索</a-button>
            <a-button key="reset" @click="resetSearchForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </header>
    <section class="main-box bg-#fff rd-4px plr-16px">
      <div class="h-52px flex-b">
        <div class="text-18px font-bold">文章列表</div>
        <div>
          <a-space>
            <a-button type="primary" size="middle" @click="toAddArticlePage">新增文章</a-button>
            <a-button type="primary" size="middle" @click="exportArticle">导出文章</a-button>
          </a-space>
        </div>
      </div>
      <div class="main-content" ref="mainContentRef">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :pagination="pageSet"
          :scroll="{ x: 1500, y: tableHeight }"
          :locale="{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }"
          @change="handleTableChange"
        >
          <template #bodyCell="{ index, column, record }">
            <template v-if="column.key === 'index'">
              <div>{{ index + 1 }}</div>
            </template>
            <template v-if="column.key === 'cover'">
              <a-image :src="record.cover" width="150px" height="200px" fallback="@/assets/images/not-imag.png"></a-image>
            </template>
            <template v-if="column.key === 'classification'">
              <div>{{ record.classification?.name || '-' }}</div>
            </template>
            <template v-if="column.key === 'operation'">
              <a-space>
                <a-button size="small">查看</a-button>
                <a-button type="primary" size="small">编辑</a-button>
                <a-popconfirm title="确定删除?" @confirm="onDelete(record as TableRowFeilds)">
                  <a-button danger size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </section>
  </section>
</template>

<script setup lang="ts">
import type { TableColumnsType, TableProps } from 'ant-design-vue'
import { SelectProps } from 'ant-design-vue/es/vc-select'
import { Pagination, SearchForm, TableRowFeilds } from '../types'
import { ArticleService, CategoryService } from '@/api'
defineOptions({ name: 'ArticleList' })

const route = useRoute()
const router = useRouter()

enum CURDTYPE {
  新增 = 1,
  修改 = 2,
  查看 = 3,
  删除 = 4,
}
// 分页器配置
const pageSet = ref<Pagination>({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ['10', '20', '30', '50', '100'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `总数：${total} 条`
  },
})

const searchRormRef = ref()
const searchFormState = reactive<SearchForm>({
  title: '',
  keywords: '',
  classificationId: '',
  sortReadNum: '',
  sortLikeNum: '',
  sortCommentNum: '',
})
// 搜索表单提交
function onFinishSearch(values: SearchForm): void {
  console.log('Search-Params:', values)
  pageSet.value.current = 1
  getListData()
}
// 重置搜索表单
function resetSearchForm(): void {
  searchRormRef.value.resetFields()
  pageSet.value.current = 1
  getListData()
}
const disabledSeachBtn = computed(() => {
  return !(searchFormState.title || searchFormState.keywords || searchFormState.classificationId)
})

const mainContentRef = ref<HTMLElement | null>(null)
const tableHeight = ref<number>(500)

const columns: TableColumnsType = [
  { title: '序号', width: 80, dataIndex: 'index', key: 'index', fixed: 'left', align: 'center' },
  { title: '封面', dataIndex: 'cover', key: 'cover', minWidth: 150 },
  { title: '标题', minWidth: 100, dataIndex: 'title', key: 'title' },
  { title: '分类', dataIndex: 'classification', key: 'classification', minWidth: 150 },
  // { title: '文章状态', dataIndex: 'status', key: 'status', minWidth: 150 },
  { title: '关键词', dataIndex: 'keywords', key: 'keywords', minWidth: 150 },
  { title: '描述', dataIndex: 'description', key: 'description', minWidth: 150 },
  { title: '时间', dataIndex: 'createTime', key: 'createTime', minWidth: 150 },
  { title: '阅读量', dataIndex: 'readNum', key: 'readNum', sorter: true, minWidth: 150 },
  { title: '点赞数', dataIndex: 'likeNum', key: 'likeNum', sorter: true, minWidth: 150 },
  { title: '评论数', dataIndex: 'commentNum', key: 'commentNum', sorter: true, minWidth: 150 },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 240,
  },
]

const tableLoading = ref<boolean>(false)
const tableData = ref<TableRowFeilds[]>([])

const onDelete = async (record: TableRowFeilds) => {
  const row = toRaw(record)
  console.log('onDelete:==>', row)
  const res = await ArticleService.remove(row?.id)
  if (res?.success) {
    window.$message.success('删除标签成功！')
    getListData()
    return true
  } else {
    window.$message.error('删除标签失败！' + res?.message)
    return false
  }
}

// 分类下拉选项
const classificationOptions = ref<SelectProps['options']>([])
function getClassificationOptions() {
  CategoryService.list().then((res) => {
    console.log('获取所有分类列表:==>', res)
    const list = res?.data || []
    classificationOptions.value = list.map((item: any) => {
      return {
        value: item?.id,
        label: item?.name,
      }
    })
  })
}
function handleTableChange(pag: { pageSize: number; current: number }, filters: any, sorter: any): TableProps['onChange'] {
  console.log('pag:==>', pag)
  console.log('filters:==>', filters)
  console.log('sorter:==>', sorter)
  if (sorter.field === 'readNum') {
    searchFormState.sortReadNum = sorter.order
  }
  if (sorter.field === 'likeNum') {
    searchFormState.sortLikeNum = sorter.order
  }
  if (sorter.field === 'commentNum') {
    searchFormState.sortCommentNum = sorter.order
  }
  pageSet.value = Object.assign(pageSet.value, pag)
  getListData()
  return
}
// 获取列表数据
async function getListData() {
  tableLoading.value = true
  const params: ArticleEntity.SearchParams = {
    page: pageSet.value.current,
    pageSize: pageSet.value.pageSize,
    title: searchFormState.title,
    keywords: searchFormState.keywords,
    classificationId: searchFormState.classificationId,
    sortReadNum: searchFormState.sortReadNum,
    sortLikeNum: searchFormState.sortLikeNum,
    sortCommentNum: searchFormState.sortCommentNum,
  }
  const res = await ArticleService.page(params)
  console.log('getList：==>', res)
  if (res?.success) {
    const list = res?.data?.list || []
    tableData.value = list
    pageSet.value.total = res?.data?.total || 0
  } else {
    tableData.value = []
  }
  tableLoading.value = false
}

// 跳到新增文章页面
function toAddArticlePage() {
  console.log('跳到新增文章页面')
  router.push('/article/add')
}

// 导出文章
function exportArticle() {
  console.log('导出文章')
}

onMounted(() => {
  if (mainContentRef.value) {
    tableHeight.value = mainContentRef.value.offsetHeight - 64
  }
  getListData()
  getClassificationOptions()
  // console.log('tableHeight:==>', tableHeight.value)
})
</script>

<style lang="scss" scoped>
.main-box {
  width: 100%;
  height: calc(100% - 76px);
  margin-top: 12px;

  .main-content {
    width: 100%;
    height: calc(100% - 52px);
  }
}
</style>
